package com.weichuanbo.xwdz.app;

import android.content.Context;
import android.text.TextUtils;

import com.jess.arms.http.GlobalHttpHandler;
import com.weichuanbo.xwdz.app.utils.SaveBeanUtil;
import com.weichuanbo.xwdz.mvp.model.entity.UserBean;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.Response;

/**
 * ================================================
 * 展示 {@link GlobalHttpHandler} 的用法
 * <p>
 * Created by MVPArmsTemplate
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * ================================================
 */
public class GlobalHttpHandlerImpl implements GlobalHttpHandler {
    private Context context;

    public GlobalHttpHandlerImpl(Context context) {
        this.context = context;
    }

    /**
     * 这里可以先客户端一步拿到每一次 Http 请求的结果, 可以先解析成 Json, 再做一些操作, 如检测到 token 过期后
     * 重新请求 token, 并重新执行请求
     *
     * @param httpResult 服务器返回的结果 (已被框架自动转换为字符串)
     * @param chain      {@link Interceptor.Chain}
     * @param response   {@link Response}
     * @return
     */
    @Override
    public Response onHttpResultResponse(String httpResult, Interceptor.Chain chain, Response response) {
        /* 这里如果发现 token 过期, 可以先请求最新的 token, 然后在拿新的 token 放入 Request 里去重新请求
        注意在这个回调之前已经调用过 proceed(), 所以这里必须自己去建立网络请求, 如使用 Okhttp 使用新的 Request 去请求
        create a new request and modify it accordingly using the new token
        Request newRequest = chain.request().newBuilder().header("token", newToken)
                             .build();

        retry the request

        response.body().close();
        如果使用 Okhttp 将新的请求, 请求成功后, 再将 Okhttp 返回的 Response return 出去即可
        如果不需要返回新的结果, 则直接把参数 response 返回出去即可*/
        return response;
    }

    /**
     * 这里可以在请求服务器之前拿到 {@link Request}, 做一些操作比如给 {@link Request} 统一添加 token 或者 header 以及参数加密等操作
     *
     * @param chain   {@link Interceptor.Chain}
     * @param request {@link Request}
     * @return
     */
    @Override
    public Request onHttpRequestBefore(Interceptor.Chain chain, Request request) {
        /* 如果需要再请求服务器之前做一些操作, 则重新返回一个做过操作的的 Request 如增加 Header, 不做操作则直接返回参数 request
        return chain.request().newBuilder().header("token", tokenId)
                              .build(); */
        return request;
    }
/*
    @Override
    public Request onHttpRequestBefore(Interceptor.Chain chain, Request request) {
        *//* 如果需要再请求服务器之前做一些操作, 则重新返回一个做过操作的的 Request 如增加 Header, 不做操作则直接返回参数 request
        return chain.request().newBuilder().header("token", tokenId)
                              .build(); *//*
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.putAll(getCommonMap());
        paramsMap.put("sign", SignCheckUtil.getSign(paramsMap));//生成并添加签名
        RequestBody body = request.body();
        // process post body inject
        if (paramsMap != null && paramsMap.size() > 0 && request.method().equals("POST") && null != body) {
            RequestBody newBody = null;
            if (body instanceof FormBody) {
                newBody = addParamsToFormBody((FormBody) body,paramsMap);
            } else if (request.body() instanceof MultipartBody) {
                newBody = addParamsToMultipartBody((MultipartBody) body,paramsMap);
            }
            if (null != newBody) {
                Request newRequest = request.newBuilder()
                        .url(request.url())
                        .method(request.method(), newBody)
                        .build();
                return newRequest;
            }
        }

        return request;
    }*/


   /* private MultipartBody addParamsToMultipartBody(MultipartBody body, Map<String, Object> paramsMap) {
        MultipartBody.Builder builder = new MultipartBody.Builder();
        MultipartBody.Builder multipartBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        Iterator iterator = paramsMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = (Map.Entry) iterator.next();
            multipartBuilder.addFormDataPart((String) entry.getKey(), (String) entry.getValue());
        }

        List<MultipartBody.Part> oldParts = (body).parts();
        if (oldParts != null && oldParts.size() > 0) {
            for (MultipartBody.Part part : oldParts) {
                multipartBuilder.addPart(part);
            }
        }
        return builder.build();
    }

    private FormBody addParamsToFormBody(FormBody body, Map<String, Object> paramsMap) {
        FormBody.Builder builder = new FormBody.Builder();
        if (paramsMap.size() > 0) {
            Iterator iterator = paramsMap.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry entry = (Map.Entry) iterator.next();
                builder.add((String) entry.getKey(), (String) entry.getValue());
            }
        }

        int paramSize = body.size();
        if (paramSize > 0) {
            for (int i = 0; i < paramSize; i++) {
                builder.add(body.name(i), body.value(i));
            }
        }
        return builder.build();
    }
    *//**
     * 配置公共参数
     * @return
     *//*
    private Map<String, String> getCommonMap() {
        Map<String, String> params = new HashMap<>();
        long serverTime = Common.Const.serverTime<1534077114? System.currentTimeMillis()/1000: Common.Const.serverTime;
        params.put("serverTime", serverTime + "");
        params.put("device", "Android");
        Object bean = SaveBeanUtil.getBean(context, Common.Const.VIPINFO);
        if (bean==null|| TextUtils.isEmpty(bean.toString()))
            return params;
        String token = ((UserBean) bean).getToken();
        if (!TextUtils.isEmpty(token) )
            params.put("token", token);
        return params;
    }*/

}
